<template>
  <div class="dashboard-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="title-card">
          <div class="title-container">
            <img
              src="/src/assets/images/ailogo.jpg"
              class="logo"
              alt="医诊系统logo"
            />
            <div class="title-content">
              <div class="system-title">智能医诊系统</div>
              <div class="current-time">{{ currentTime }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <h3>今日挂号数</h3>
          <div class="stat-number">{{ todayData.register }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <h3>今日退号数</h3>
          <div class="stat-number">{{ todayData.cancel }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <h3>接诊数量</h3>
          <div class="stat-number">{{ todayData.consultation }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card>
          <h3>科室接诊统计</h3>
          <div ref="deptChart" style="height: 400px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <h3>医生接诊排行</h3>
          <div ref="doctorChart" style="height: 400px"></div>
        </el-card>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-card style="margin-top: 5px;">
          <h3>药品发放统计</h3>
          <div ref="medicineChart" style="height: 400px"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";
import { ElMessage } from "element-plus"; // 确保引入消息组件
import {
  getTodayStats,
  getDeptStats,
  getDoctorStats,
  getMedicineStats,
} from "@/api/main/mainindex";

// 响应式数据
const todayData = ref({
  register: 0,
  cancel: 0,
  consultation: 0,
});

// 图表Ref
const deptChart = ref(null);
const doctorChart = ref(null);
const medicineChart = ref(null);

// 安全获取数据方法
const fetchData = async () => {
  try {
    const [todayRes, deptRes, doctorRes, medicineRes] = await Promise.all([
      getTodayStats().catch(() => ({ data: {} })),
      getDeptStats().catch(() => ({ data: [] })),
      getDoctorStats().catch(() => ({ data: [] })),
      //   getMedicineStats().catch(() => ({ data: [] }))
    ]);

    console.log("todayRes:", todayRes);
    // 处理今日数据
    todayData.value = {
      register: todayRes?.register || 0,
      cancel: todayRes?.cancel || 0,
      consultation: todayRes?.consultation || 0,
    };

    // 处理科室数据（即使全为0）
    initDeptChart(deptRes || []);

    // 处理医生空数据
    initDoctorChart(doctorRes || []);

    // 处理药品数据（示例）
    // initMedicineChart(medicineRes.data || []);
  } catch (error) {
    console.error("数据获取失败:", error);
    ElMessage.error("数据加载失败");
    initEmptyCharts();
  }
};

// 科室图表处理（全0数据专用）
const initDeptChart = (data) => {
  const chart = echarts.init(deptChart.value);

  // 确保数据格式正确
  const safeData = Array.isArray(data) ? data : [];

  // 提取科室信息
  const deptNames = safeData.map((d) => d.departmentName || "未知科室");
  const registerData = safeData.map((d) => d.registerCounts || 0);
  const consultationData = safeData.map((d) => d.consultationCounts || 0);

  const option = {
    title: {
      //   text: deptNames.length ? '科室接诊统计' : '暂无科室数据',
      left: "center",
      textStyle: {
        color: "#666",
      },
    },
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["挂号数", "接诊数"],
    },
    xAxis: {
      type: "category",
      data: deptNames.length ? deptNames : ["数据加载中..."], // 保证有数据
      axisLabel: {
        rotate: 30,
        interval: 0,
      },
    },
    yAxis: {
      type: "value",
      min: 0, // 强制从0开始
      minInterval: 1,
    },
    grid: {
      bottom: deptNames.length ? "20%" : "10%",
    },
    series: [
      {
        name: "挂号数",
        type: "bar",
        data: registerData,
        itemStyle: {
          color: "#5470c6",
        },
        barWidth: 30,
      },
      {
        name: "接诊数",
        type: "bar",
        data: consultationData,
        itemStyle: {
          color: "#91cc75",
        },
        barWidth: 30,
      },
    ],
  };

  chart.clear();
  chart.setOption(option);
};

// 医生图表处理（空数组专用）
const initDoctorChart = (data) => {
  const chart = echarts.init(doctorChart.value);

  const safeData = Array.isArray(data) ? data : [];
  const hasData = safeData.length > 0;

  const option = {
    title: {
      //   text: hasData ? '医生接诊排行' : '暂无接诊数据',
      left: "center",
    },
    xAxis: {
      type: "value",
      min: 0,
      minInterval: 1,
    },
    yAxis: {
      type: "category",
      data: hasData
        ? safeData.map((d) => d.docterName || "未知医生")
        : ["暂无数据"], // 保证有数据
      axisLabel: {
        interval: 0,
      },
    },
    series: [
      {
        type: "bar",
        data: hasData ? safeData.map((d) => d.consultationCount || 0) : [0], // 保证有数据
        itemStyle: {
          color: "#ee6666",
        },
      },
    ],
  };

  chart.clear();
  chart.setOption(option);
};

// 药品图表（示例）
const initMedicineChart = (data) => {
  const chart = echarts.init(medicineChart.value);

  const option = {
    title: {
      text: "药品发放统计",
      left: "center",
    },
    series: [
      {
        type: "pie",
        data: data.length ? data : [{ name: "暂无数据", value: 1 }],
        itemStyle: {
          color: data.length ? undefined : "#eee",
        },
      },
    ],
  };

  chart.clear();
  chart.setOption(option);
};

// 初始化空图表
const initEmptyCharts = () => {
  [deptChart, doctorChart, medicineChart].forEach((chart) => {
    if (chart.value) {
      echarts.dispose(chart.value);
    }
  });
};

// 新增时间相关响应式数据
const currentTime = ref("");
// 时间更新函数
const updateTime = () => {
  const now = new Date();
  currentTime.value = now.toLocaleTimeString("zh-CN", {
    hour12: false,
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

// 生命周期
onMounted(() => {
  // 初始化时间
  updateTime();
  // 启动定时器
  const timer = setInterval(updateTime, 1000);
  // 组件卸载时清除定时器
  onBeforeUnmount(() => clearInterval(timer));
  fetchData();
});

onBeforeUnmount(() => {
  initEmptyCharts();
});
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.stat-card {
  text-align: center;
  margin-bottom: 20px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-top: 10px;
}

/* 新增样式 */
.header-row {
  margin-bottom: 20px;
}

.title-card {
  height: 120px;
  background: linear-gradient(135deg, #409eff, #337ecc);
}

.title-container {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 15px;
}

.logo {
  width: 60px;
  height: 60px;
  margin-right: 15px;
}

.title-content {
  color: white;
}

.system-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}

.current-time {
  font-size: 36px;
  font-family: "Courier New", monospace;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
}

/* 调整原有卡片间距 */
.stat-card {
  margin-bottom: 5px;
}
</style>
